#include "GLShader.h"
#include <iostream>
#include <fstream>

GLShader::GLShader() :
	vertexShaderHandler(0),
	fragmentShaderHandler(0) {

}

GLShader::~GLShader() {

}

GLuint GLShader::loadShader(std::string shaderFileName, bool isVertexShader) {
	// Load vertex Shader
	GLuint shaderHandler = glCreateShader (isVertexShader? GL_VERTEX_SHADER : GL_FRAGMENT_SHADER);
	if ( 0 == shaderHandler ) {
		std::cout << "Error creating vertex shader" << std::endl;
		return 0;
	}

	std::ifstream v_shader_file(shaderFileName.c_str(), std::ifstream::in);
	std::string v_str((std::istreambuf_iterator<char>(v_shader_file)), std::istreambuf_iterator<char>());
	const char* vs_code_array[] = {v_str.c_str()};

	glShaderSource( shaderHandler, 1, vs_code_array, NULL);

	// Compilar el shader
	glCompileShader( shaderHandler );

	// verificar resultado de la compilacion
	GLint vs_compilation_result;
	glGetShaderiv( shaderHandler, GL_COMPILE_STATUS, &vs_compilation_result );
	if( GL_FALSE == vs_compilation_result )
	{
		std::cout << "shader (" << shaderFileName << ") compilation failed!\n" << std::endl;
		GLint logLen;
		glGetShaderiv( shaderHandler, GL_INFO_LOG_LENGTH, &logLen );
		if( logLen > 0 )
		{
			char * log = new char[logLen];//(char *)malloc(logLen);
			GLsizei written;
			glGetShaderInfoLog(shaderHandler, logLen, &written, log);
			std::cout << "Shader log: " << log << std::endl;
			delete [] log;//free(log);
		}
	}
	return shaderHandler;
}

GLuint GLShader::getVertexShaderHandler() {
	if (vertexShaderHandler == 0) {
		vertexShaderHandler = loadShader(config.getVertexShader(), true);
	}
	return vertexShaderHandler;
}

GLuint GLShader::getFragmentShaderHandler() {
	if (fragmentShaderHandler== 0) {
		fragmentShaderHandler = loadShader(config.getFragmentShader(), false);
	}
	return fragmentShaderHandler;
}

std::map<std::string, int> GLShader::getInputAttributes() {
	return config.getAttributesIndex();
}
